package org.example;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.example.handler.PacketHandler;
import org.example.handler.RpcResponseHandler;

public class ServerConnection {
    private final RpcResponseHandler rpcResponseHandler;
    private final Bootstrap bootstrap;
    private String index;

    public ServerConnection(String location) throws InterruptedException {
        rpcResponseHandler = new RpcResponseHandler();
        bootstrap = new Bootstrap();
        this.index = location;
        String[] split = location.split(":");
        initConnection(split[0], Integer.parseInt(split[1]));
    }

    private void initConnection(String ip, int port) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();

        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new PacketHandler());
                        pipeline.addLast(rpcResponseHandler);
                    }
                });

        bootstrap.connect(ip, port).sync();
    }

    public RpcResponseHandler getRpcResponseHandler() {
        return rpcResponseHandler;
    }

    public Bootstrap getBootstrap() {
        return bootstrap;
    }

    public String getIndex() {
        return index;
    }
}
